<?php
class sms_model_system extends sms_model_data {
	const MSG_T_ALL = 0;
	const MSG_T_FRIREQ = 1;
	const MSG_T_GIFT = 2;
	const MSG_T_SKILL = 3;
	const MSG_CITE = 4;
	var $msgType = array(
		self::MSG_T_ALL => 0, //所有消息
		self::MSG_T_FRIREQ => '[:friends|add:]', //好友请求
		self::MSG_T_GIFT => '[:gift:]', //礼物类型
		self::MSG_T_SKILL => '[:buff:]', // 技能类型
		self::MSG_CITE => '[:cite:]' //转帖类型
	);
	public function __construct(){
		parent::__construct();
		$this->table = 'app_sms_notice';
		$this->reltable = 'app_sms_notice_reciever';
	}
	/**
	 * 发送短消息接口：
	 *
	 * @param array $args
	 * @return int ;
	 */
	public function add($args){ 
		$args = filter_params($args, 'senderid', 'sender','recieverid', 'reciever', 'content', 'target');
		trim_params($args);
		$args['dateline'] = time();
		if($id = $this->db->insert($this->table, $args)){
			$target = unserialize($args['target']);
			$target['id'] = $id;
			$sql = 'UPDATE '.$this->table.' SET target =&target  WHERE sms_id=&id';
			$para = array(
						'id' =>$id,
						'target' => serialize($target)
					);
			$this->db->query($sql,$para);
			return $id;
		}
		return false;
	}
	
	/**
	 * 发送短消息-添加会话关系接口
	 *
	 * @param unknown_type $args
	 * @return unknown
	 */
	public function addRel($args){
		$args = filter_params($args, 'sms_id', 'reciever_id','reciever', 'readed');
		trim_params($args);
		if($msid = $this->db->insert($this->reltable, $args))
			$this->updateNoticeNums($args,1);
		return $msid?$msid:false;
	}
	
	/**
	 * 更新未读系统消息数
	 *
	 * @param unknown_type $param
	 * @param unknown_type $type
	 */
	private   function updateNoticeNums(&$param,$type=1){
		if($param['senderid']==0 ){
			if(strpos($param['sender_name'],':friends|add:') !==false){
				$type = self::MSG_SYS_FRIENDS ;
			}
			elseif (strpos($param['sender_name'],':buff:') !==false){
				$type = self::MSG_SYS_BUFF  ;
			}
			elseif(strpos($param['sender_name'],':gift:') !==false){
				$type = self::MSG_SYS_GIFT   ;
			}
			else $type = self::MSG_SYS_SMS_CNT;
		}
		$data = $this->factory('sms_model_data');
		if(is_array($param['reciever_id']) && !empty($param['reciever_id'])){
			foreach ($param['reciever_id'] as $v){
				$data->updateSmsCount($v,$type,1);
			}
		}else{
			$data->updateSmsCount($param['reciever_id'],$type,1);
		}
		unset($data);
		return ;
	}
	/**
	 * 删除系统消息
	 *
	 * @param unknown_type $uid
	 * @param unknown_type $id
	 * @return unknown
	 */
	public function removeSystem($uid,$id='',$type = 0){
		if(!$uid) return false;
		$sql = 'UPDATE '.$this->reltable.' SET isdelete = 1  WHERE reciever_id=&uid ';
		if($id){
			if(is_array($id) && !empty($id)){
				$id = implode(',',$id);
			}
			$sql .= ' AND sms_id IN ('.$id.')';
		}
		if($type>0 && $this->msgType[$type]){
			$sql .= ' AND sender = \''.$this->msgType[$type].'\' ';
		}
		$params = array('uid'=>$uid);
		return $this->db->query($sql, $params);
	}
	
	/**
	 * 获取系统收件箱列表
	 *
	 * @param unknown_type $uid
	 * @param unknown_type $page
	 * @param unknown_type $pageSize
	 * @param unknown_type $type
	 * @return unknown
	 */
	public function selectSysInboxPage($uid, $page, $pageSize,$type = ''){
		$msgtype = '';
		if($type!=='' && array_key_exists($type,$this->msgType)){
			$msgtype = $this->parseSenderNames($this->msgType[$type]);
		}
		$sql = 'SELECT a.sms_id,a.senderid AS sender_id,a.sender AS sender_name,a.content,a.dateline AS create_time,a.target,b.readed AS unread FROM '.$this->table.' a,'.$this->reltable.' b WHERE a.sms_id = b.sms_id AND b.reciever_id='.$uid.' AND b.isdelete=0 '.($msgtype?'AND a.sender = \''.$msgtype.' \'':'').'ORDER BY a.sms_id DESC ';
		$params = array('uid'=>$uid);
		return $this->db->selectPageSimple($sql, $params, $page, $pageSize );
	}
	private function parseSenderNames($str){
		$regex = "`\[\:([a-z0-9]+)(?:\|[a-z0-9]+)?\:\]`";
		$flag = preg_match($regex, $str, $match);
		if($flag){
			return $match[0];
		}else{
			return NULL;
		}
	}
	/**
	 * 获取单条短消息信息
	 *
	 * @param unknown_type $sms_id
	 * @return unknown
	 */
	public function select($sms_id){
		$sql = "SELECT a.sms_id,a.sms_title,a.sms_content,a.sms_sender,a.sms_senderid,a.sms_reciver,a.sms_reciverid,a.sms_pid,a.sms_total_num,a.sms_duplicate,a.sms_dateline,a.sms_isdelete  FROM ".$this->table." a WHERE a.sms_id=&id";
		$params = array('id'=>$sms_id);
		return $this->db->fetchRow($sql, $params);
	}
	/**
	 * 获取各种未读消息数
	 *
	 * @param unknown_type $uid
	 * @return unknown
	 */
	public function queryUnReadSms($uid){
		if(!is_numeric($uid)) return false;
		$sql = "SELECT asc_sms as smsnum,asc_sysann as sysnum,asc_comment as comnum,asc_message as msgnum,asc_friends as friendsnum,asc_buff as buffnum,asc_gift as giftnum FROM app_sms_count WHERE uid=&uid ";
		$params = array('uid' =>$uid);
		if($rst = $this->db->fetchRow($sql, $params)){
			return $rst;
		}
		return false;
	}
	/**
	 * 更新消息状态
	 *
	 * @param unknown_type $id
	 * @param unknown_type $target
	 * @return unknown
	 */
	public function updateTarget($id, $target){
		$sql = 'UPDATE '.$this->table." SET target=&target WHERE sms_id=&id" ;
		$target['id'] = $id;
		$params = array(
			'id'=>$id,
			'target'=>serialize($target)
		);
		return $this->db->query($sql, $params);
	}
	
	/**
	 * 回滚事务
	 *
	 * @param unknown_type $sms_id
	 * @param unknown_type $type
	 * @return unknown
	 */
	public function rollback($sms_id,$type=true){
		$sql = "DELETE from ".($type?$this->table:$this->reltable)." where sms_id=&sms_id";
		$params = array('sms_id'=>$sms_id);
		return $this->db->query($sql, $params);
	}
}